import React from 'react'
import { connect } from 'react-redux';

export default function asyncComponent (importComponent) {
  class AsyncComponent extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        component: null
      }
    }
    componentDidMount () {
      this.routeGuard() // 路由守卫
    }
    /**
     * 路由守卫
     */
    routeGuard () {
      const { userInfo, setUserInfo } = this.props
      // 用户处于登陆状态
      if (userInfo.token) {
        this.loadComponent()
      } else {
        // 用户未登录
        setUserInfo({
          userName: 'zhangsan',
          userId: 'abcd',
          token: '1234'
        })
        this.loadComponent()
      }
    }
    loadComponent () {
      importComponent().then(mod => {
        this.setState({
          component: mod.default ? mod.default : mod
        })
      })
    }
    render () {
      const C = this.state.component
      return C ? <C {...this.props} /> : null
    }
  }


  /**
 * @description: 需要渲染什么数据
 */
  function mapStateToProps (state) {
    return {
      userInfo: state.userInfo
    }
  }
  /**
   * @description: 需要触发什么行为
   */
  function mapDispatchToProps (dispatch) {
    return {
      setUserInfo: (data) => dispatch({ type: 'userInfo', data })
    }
  }

  return connect(mapStateToProps, mapDispatchToProps)(AsyncComponent)
}